var bookVideo;
var book;
var videoId;
var userFrom;
//视频状态：0 首次播放，1 播放中，2 暂停，3 结束
var videoStatus = 0;
//视频观看时长记录
var videoDuration = 0;

//视频开始时间
var startTime = 0;

//临时播放时间
var tempDuration = 0;

//定时方法（结束时使用）
var timerMethod;

var my_timer;

var globalId;

var u = navigator.userAgent;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;

// 媒体类型 1音频，2视频 未知： 9
var mediaType = 9

var player;

var userId;

var replSour = "http://evideo.adp5.com.cn/";
var replTar = "http://dxkt.daxiang.cn/dxkt-files/adp5qrcode/";

let logger = new window.Tracker('cn-qingdao.log.aliyuncs.com', 'jzxl', 'dx-exue');

let voiceLogger = new window.Tracker('cn-qingdao.log.aliyuncs.com', 'jzxl', 'voice-click-log');

var initPlayer = function (source) {
    player = new Aliplayer({
            "id": "my_video",
            "source": source,
            "width": "100%",
            "autoplay": false,
            "x5_type": "h5",
            "isLive": false,
            "rePlay": false,
            "playsinline": true,
            "preload": true,
            "controlBarVisibility": "always",
            "useH5Prism": true,
            "skinLayout": [
                {
                    "name": "bigPlayButton",
                    "align": "blabs",
                    "x": 30,
                    "y": 80
                },
                {
                    "name": "H5Loading",
                    "align": "cc"
                },
                {
                    "name": "errorDisplay",
                    "align": "tlabs",
                    "x": 0,
                    "y": 0
                },
                {
                    "name": "infoDisplay"
                },
                {
                    "name": "tooltip",
                    "align": "blabs",
                    "x": 0,
                    "y": 56
                },
                {
                    "name": "thumbnail"
                },
                {
                    "name": "controlBar",
                    "align": "blabs",
                    "x": 0,
                    "y": 0,
                    "children": [
                        {
                            "name": "progress",
                            "align": "blabs",
                            "x": 0,
                            "y": 44
                        },
                        {
                            "name": "playButton",
                            "align": "tl",
                            "x": 15,
                            "y": 12
                        },
                        {
                            "name": "timeDisplay",
                            "align": "tl",
                            "x": 10,
                            "y": 7
                        },
                        {
                            "name": "fullScreenButton",
                            "align": "tr",
                            "x": 10,
                            "y": 12
                        }
                    ]
                }
            ]
        }, function (player) {
            console.log("The player is created");
        }
    );

    player.on('play', playF);
    player.on('pause', pauseF);
    player.on('ended', endedF);

    player.on("x5requestFullScreen", function (e) {
        $("#info").addClass("sc");
    })
    player.on('x5cancelFullScreen', function (e) {
        $("#info").removeClass("sc");
    })

}

var getUserInfo = function () {
    $.ajax({
        type: "POST",
        url: "../api/home/getUserInfo",
        contentType: "application/x-www-form-urlencoded",
        success: function (r) {
            if (r.code === 0) {
                console.log("获取用户身份");
                console.log(r);
                userId = r.userId;
                var qrcode = new QRCode(document.getElementById("qrcodeNode"), {
                    width : 100,
                    height : 100
                });
                qrcode.makeCode("https://da-an.adp5.cn/mp-qr?type=1&id=" + videoId +"&userId=" + userId);
                let mycanvas = document.getElementsByTagName("canvas")[0];
                let image = convertCanvastoImage(mycanvas);
                $("#qrcode").append(image);
            } else {
                $.toast(r.msg, "text");
            }
        }
    });
}
var convertCanvastoImage = function(canvas){
    var image = new Image();
    image.src = canvas.toDataURL("image/png");
    return image;
}
var showSelectIdent = function () {
    $.modal({
        title: "身份",
        text: "请选择您的身份，我们之后会根据您选择的身份给你推送对应的内容，请慎重选择",
        buttons: [
            {
                text: "学生", onClick: function () {
                    setIdent(0)
                }
            },
            {
                text: "家长", onClick: function () {
                    setIdent(1)
                }
            },
            {
                text: "老师", onClick: function () {
                    setIdent(2)
                }
            },
        ]
    });
}
var setIdent = function (ident) {
    $.ajax({
        type: "POST",
        url: "../api/default/saveUserIdentity",
        data: {
            identity: ident
        },
        contentType: "application/x-www-form-urlencoded",
        success: function (r) {
            if (r.code === 0) {
                $.toast("设置身份成功", "text");
            } else {
                $.toast(r.msg, "text");
            }
        }
    });
}

//获取视频详情
var getVideoDetail = function () {
    $.ajax({
        type: "POST",
        url: "../api/video/getDetail",
        data: {
            videoId: videoId
        },
        contentType: "application/x-www-form-urlencoded",
        success: function (r) {
            if (r.code === 0) {
                console.log("获取视频详情")
                console.log(r)
                if(r.bookVideo.videoUrl){
                    r.bookVideo.videoUrl = r.bookVideo.videoUrl.replace(replSour,replTar)
                }
                if(r.bookVideo.resourceUrl){
                    r.bookVideo.resourceUrl = r.bookVideo.resourceUrl.replace(replSour,replTar)
                }
                bookVideo = r.bookVideo;
                book = r.bookVideo.book;
                fillDetailData();
                fillVideoData(r.moreBookVideoList);
            } else {
                $.toast(r.msg, "text");
            }
        }
    });
}

var fillDetailData = function () {
    var baseInfo = book.grade.name + ">" + book.subject.name + ">" + book.version.name + ">" + book.season.name;
    $("#base-info").html(baseInfo);
    $("#video-info").html(bookVideo.videoName);

    if (bookVideo.videoUrl) {
        $("#my_video").css("display", "block");
        setMediaType(bookVideo.videoUrl)
        initPlayer(bookVideo.videoUrl);
        // 如果存在视频，则显示后台播放按钮
        $(".flex-container").css("display", "flex");
    }
    if (bookVideo.resourceUrl) {
        if (bookVideo.videoUrl) {
            $("#download-resources-button").css("display", "inline");
            $("#download-resources-button").attr("href", bookVideo.resourceUrl);

        } else {
            $(".cover-img").css("display", "block");
            if (isAndroid) {
                $("#android-download-resources-home").css("display", "inline");
            }
            $(document).on("click", "#download-resources-home", function () {
                if (isAndroid) {
                    window.open('../public/plugins/pdfjs/web/viewer.html?file=' + bookVideo.resourceUrl.replace(replTar,replSour), 'PDF', 'width:50%;height:50%;top:100;left:100;');
                } else {
                    window.location.href = bookVideo.resourceUrl;
                }
            });

            $(document).on("click", "#android-download-resources-home", function () {
                window.location.href = bookVideo.resourceUrl;
            });

        }
    }

}
var fillVideoData = function (videoList) {
    var html = '';
    videoList.forEach(function (value, index, array) {
        html += '<a class="weui-cell weui-cell_access" href="./video_detail.html?videoId=' + value.id + '">';
        html += '<div class="weui-cell__hd"><p class="page-no"><b>' + value.pageNo + '</b><span style="font-size:10px">页</span></p></div>';
        html += '<div class="weui-cell__bd">';
        html += '<p >' + value.videoName + '</p>';
        html += '<p style="font-size: 13px;color: #888888;">' + value.unitName + '</p>';
        html += '</div>';
        html += '<div class="weui-cell__ft"></div>';
        html += '</a>';
    });
    $("#showVideoList").html(html);
}

$(document).on("click", "#video-more", function () {
    /* <![CDATA[ */
    window.location.href = "./video-list.html?gradeId=" + book.gradeId + "&subjectId=" + book.subjectId;
    /* ]]> */
});

$(document).on("click", "#goHome", function () {
    /* <![CDATA[ */
        var host ="./subject-list.html";
        if(!book.name.startsWith("基础训练")){
            host = "./video-list.html?gradeId=" + book.gradeId + "&subjectId=" + book.subjectId;
        }
        window.location.href = host;
    /* ]]> */
})

$(document).on("click", "#test-button", function () {
    setClick(1);
});


var setMediaType = function(url){
    var suffix = url.substr(url.length - 3, url.length)
    suffix = suffix.toLowerCase();
    if (suffix === "mp3") {
        mediaType = 1;
    } else {
        mediaType = 2;
    }
}

$(document).on("click", "#voice", function () {
    if (bookVideo.videoUrl) {
        voiceLogger.push('from', 1);
        voiceLogger.push('userId', userId);
        voiceLogger.push('globalId',globalId);
        voiceLogger.push('buttonType', mediaType);
        voiceLogger.logger();
    }

});
//上报
//计时,并且上报
my_timer = function () {
    //设置当前时间
    tempDuration = Date.parse(new Date());
    //videoDuration暂停时会满足，实时上报会
    if (tempDuration - startTime > 15000) {
        videoDuration += tempDuration - startTime;
        startTime = Date.parse(new Date());
        userVideoRecord(videoDuration, "1");
    }
}

//绑定视频事件
//开始/继续 开始为0,继续为1

var playF = function () {
    startTime = Date.parse(new Date());
    timerMethod = window.setInterval("my_timer()", 500);
    console.log("执行了，定时后的代码");
    if (videoStatus == 0) {
        //上报
        setViews();
        userVideoRecord(videoDuration, "0");
    }
    videoStatus = 1;
}

//暂停
var pauseF = function () {
    //当前时间-开始时间
    videoDuration += tempDuration - startTime;
    window.clearInterval(timerMethod);
    //观看时长>2以后进行上报
    if (tempDuration - startTime > 5000) {
        userVideoRecord(videoDuration, "2");
    }
    videoStatus = 2;
}
//结束
var endedF = function () {
    console.log("播放结束100006");
    videoStatus = 3;
    videoDuration += tempDuration - startTime;
    window.clearInterval(timerMethod);
    startTime = Date.parse(new Date());
    tempDuration = Date.parse(new Date());
    userVideoRecord(videoDuration, "3");
}

//页面生成24位uuid
function guid() {
    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(24).substring(1);
    }

    return (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4());
}

var initPutVideoInfo = function () {
    sendTest(0);
    globalId = guid();
    pushHistory();
    window.addEventListener("popstate", function (e) {
        console.log("进入退出页面方法");
        //进行中退出
        if (videoStatus == 1) {
            //计算观看时间，上报
            videoDuration += tempDuration - startTime;
            userVideoRecord(videoDuration, "4");
        }
        window.history.go(-1);
    }, false);

    function pushHistory() {
        var state = {
            title: "title",
            url: "#"
        };
        window.history.pushState(state, "title", "#");
    }
}

var userVideoRecord = function (duration, status) {
    console.log(duration);
    duration = duration == 0 ? 0 : duration / 1000;
    var totalTime = $("#my_video")[0].duration;
    if (isNaN(totalTime)) {
        totalTime = 0;
    }

    logger.push('userId', userId);
    logger.push('globalId', globalId);
    logger.push('duration', duration);
    logger.push('userFrom', userFrom);
    logger.push('videoStatus', status);
    logger.push('videoId', bookVideo.id);
    logger.push('totalTime', totalTime);
    logger.push('mediaType', mediaType);
    logger.push('currentTime', parseInt($("#my_video")[0].currentTime));
    logger.logger();
}

//获取统计信息
var getCountInfo = function () {
    $.ajax({
        type: "POST",
        url: "../api/default/getCount",
        data: {
            videoId: videoId
        },
        contentType: "application/x-www-form-urlencoded",
        success: function (r) {
            if (r.code === 0) {
                console.log("获取统计信息成功")
                console.log(r)
                console.log(r.count)
                if (r.count) {
                    if (r.count.zan) {
                        $("#click-count").text(r.count.zan);
                    } else {
                        $("#click-count").text(0);
                    }
                    if (r.count.viewNumber) {
                        $("#view-count").text(r.count.viewNumber);
                    } else {
                        $("#view-count").text(0);
                    }
                } else {
                    $("#view-count").text(0);
                    $("#click-count").text(0);
                }

                if (r.isClick) {
                    $('#zan-style').addClass('icon-38');
                } else {
                    $('#zan-style').addClass('icon-65');
                }
            }
        }
    });
}

//设置点赞信息
var setZan = function (status) {
    $.ajax({
        type: "POST",
        url: "../api/default/setZan",
        data: {
            videoId: videoId,
            status: status
        },
        contentType: "application/x-www-form-urlencoded",
        success: function (r) {
            if (r.code === 0) {
                console.log("设置点赞成功")
                console.log(r)
            }
        }
    });
}
//设置视频总观看数
var setViews = function () {
    $.ajax({
        type: "POST",
        url: "../api/default/setViews",
        data: {
            videoId: videoId
        },
        contentType: "application/x-www-form-urlencoded",
        success: function (r) {
            if (r.code === 0) {
                console.log("设置视频观看成功")
                console.log(r)
                var val = $("#view-count").text();
                $("#view-count").text(parseInt(val) + 1);
            }
        }
    });
}
//绑定点击事件
$(document).on("click", ".click-method", function () {
    if ($('#zan-style').hasClass('icon-38')) {
        $('#zan-style').removeClass('icon-38').addClass('icon-65');
        var val = $("#click-count").text();
        if (parseInt(val) > 0) {
            $("#click-count").text(parseInt(val) - 1);
            setZan(0);
        }
    } else {
        $('#zan-style').addClass('icon-38').removeClass('icon-65');
        var val = $("#click-count").text();
        $("#click-count").text(parseInt(val) + 1);
        setZan(1);
    }
});

$(document).on("click", "#dongle", function () {
    sendTest(1);
});
$(document).on("click", "#budong", function () {
    sendTest(2);
});

//发送测试方法
var sendTest = function (status) {
    $.ajax({
        type: "POST",
        url: "../api/home/setUserVideoInfo",
        data: {
            videoId: videoId,
            status: status
        },
        contentType: "application/x-www-form-urlencoded",
        success: function (r) {
            if (r.code === 0) {
                console.log("设置成功")
                console.log(r)
                if (status === 1) {
                    alert("你的进步神速，真棒！");
                } else if (status === 2) {
                    alert("建议再仔细看一遍，加油！");
                }
            }
        }
    });
}
